package cn.demomaster.quickui_sample.ui.fragment.helper;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.demomaster.quickcompat.service.ServiceHelper;

import cn.demomaster.quickevent.core.QuickEvent;
import cn.demomaster.quickevent.core.Subscribe;
import cn.demomaster.quickevent.core.ThreadMode;
import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickpermission.QuickPermission;
import cn.demomaster.quickpermission.listener.PermissionResultCallback;
import cn.demomaster.quickrouter.fragment.QuickFragment;
import cn.demomaster.quickui.annotation.ActivityPager;
import cn.demomaster.quickui.annotation.ResType;
import cn.demomaster.quickui.helper.BatteryOptimizationsHelper;
import cn.demomaster.quickui.model.EventMessage;
import cn.demomaster.quickui.service.DebugFloatingService;
import cn.demomaster.quickui.service.FpsFloatingService;
import cn.demomaster.quickui.service.LifecycleFloatingService;
import cn.demomaster.quickui_sample.R;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

/**
 * Squirrel桓
 * 2018/8/25
 */
@ActivityPager(name = "悬浮窗", preViewClass = TextView.class, resType = ResType.Custome)
public class FloatingFragment extends QuickFragment {

    Button btn_floating_01;
    Button btn_floating_02;
    Button btn_floating_03;
    Button btn_floating_04;
    Button btn_floating_05;
    Button btn_floating_06;

    @NonNull
    @Override
    public View onGenerateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_layout_floating, null);
        return mView;
    }

    public void initView(View rootView) {
        btn_floating_01 = findViewById(R.id.btn_floating_01);
        btn_floating_02 = findViewById(R.id.btn_floating_02);
        btn_floating_03 = findViewById(R.id.btn_floating_03);
        btn_floating_04 = findViewById(R.id.btn_floating_04);
        btn_floating_05 = findViewById(R.id.btn_floating_05);
        btn_floating_06 = findViewById(R.id.btn_floating_06);
        QuickEvent.getDefault().register(this);

        btn_floating_01.setOnClickListener(v -> {
            QuickPermission.with(getActivity()).permissions(new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW})
                    .onGranted(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            boolean exist = ServiceHelper.serverIsRunning(mContext, FpsFloatingService.class.getName());
                            if (exist) {
                                ServiceHelper.stopService(mContext, FpsFloatingService.class);
                            } else {
                                ServiceHelper.startService(mContext, FpsFloatingService.class);
                            }
                            return null;
                        }
                    }).request();
        });

        btn_floating_02.setOnClickListener(v -> {QuickPermission.with(getActivity()).permissions(new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW})
                .onGranted(new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        //                        boolean exist = ServiceHelper.serverIsRunning(mContext, FloatingMenuService.class.getName());
//                        if (exist) {
//                            ServiceHelper.stopService(mContext,FloatingMenuService.class);
//                        } else {
//                            ServiceHelper.startService(mContext, FloatingMenuService.class);
//                        }
                        return null;
                    }
                }).request();
        });

        btn_floating_03.setOnClickListener(v -> {
            QuickPermission.with(getActivity()).permissions(new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW})
                .onGranted(new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        boolean exist = ServiceHelper.serverIsRunning(mContext,DebugFloatingService.class.getName());
                        if (exist) {
                            ServiceHelper.stopService(mContext,DebugFloatingService.class);
                        } else {
                            ServiceHelper.startService(mContext, DebugFloatingService.class);
                        }
                        return null;
                    }
                }).request();
        });
        btn_floating_04.setOnClickListener(v -> {QuickPermission.with(getActivity()).permissions(new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW})
                .onGranted(new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        boolean exist = ServiceHelper.serverIsRunning(mContext,LifecycleFloatingService.class.getName());
                        if (exist) {
                            ServiceHelper.stopService(mContext,LifecycleFloatingService.class);
                        } else {
                            ServiceHelper.startService(mContext, LifecycleFloatingService.class);
                        }
                        return null;
                    }
                }).request();
        });
        btn_floating_05.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                BatteryOptimizationsHelper.requestIgnoreBatteryOptimizations(getContext());
            }
        });
        btn_floating_06.setOnClickListener(v -> BatteryOptimizationsHelper.requestAutoStartService(getContext()));
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnServiceChanged(EventMessage eventMessage){
        if(eventMessage!=null) {
            //QdLog.println(eventMessage.toString());
            if (!TextUtils.isEmpty(eventMessage.key) && eventMessage.key.equals("QDFloatingService2-onCreate")) {
                if (eventMessage.data[0] == FpsFloatingService.class) {
                    btn_floating_01.setText(((int) eventMessage.data[1]) == 0 ? "关闭悬浮" : "打开悬浮");
                }
//                if (eventMessage.data[0] == FloatingMenuService.class) {
//                    btn_floating_02.setText(((int) eventMessage.data[1]) == 0 ? "关闭悬浮" : "打开悬浮");
//                }
                if (eventMessage.data[0] == DebugFloatingService.class) {
                    btn_floating_03.setText(((int) eventMessage.data[1]) == 0 ? "关闭控制台" : "开启控制台");
                }
                if (eventMessage.data[0] == LifecycleFloatingService.class) {
                    btn_floating_04.setText(((int) eventMessage.data[1]) == 0 ? "关闭生命周期监控器" : "开启生命周期监控器");
                }
            }
        }
    }
/*
    //跳转到设置-请求悬浮窗权限
    @TargetApi(Build.VERSION_CODES.M)
    public static void getOverlayPermission(Activity context) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivityForResult(intent, 123456);
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Intent intent1 = new Intent(context, DialogWindowActivity.class);
                context.startActivity(intent1);
                // 参数1：SecondActivity进场动画，参数2：MainActivity出场动画
                context.overridePendingTransition(R.anim.fade_in, 0);
            }
        });
    }*/

    @Override
    public void onDestroy() {
        super.onDestroy();
        QuickEvent.getDefault().unRegister(this);
    }
}